package zhoufu.sz.sanxiao_check.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.inject.Inject;

import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import eu.davidea.flexibleadapter.FlexibleAdapter;
import eu.davidea.viewholders.FlexibleViewHolder;
import zhoufu.sz.sanxiao_check.R;
import zhoufu.sz.sanxiao_check.databinding.ItemShowpicBinding;
import zhoufu.sz.sanxiao_check.inject.components.LoginComponet;
import zhoufu.sz.sanxiao_check.models.CheckItemModel;
import zhoufu.sz.sanxiao_check.models.DangerModel;
import zhoufu.sz.sanxiao_check.navigation.Navigator;
import zhoufu.sz.sanxiao_check.ui.FireSafeActivity;
import zhoufu.sz.sanxiao_check.ui.adapter.FireSubItemAdapter;
import zhoufu.sz.sanxiao_check.ui.adapter.items.DataBindingItem;
import zhoufu.sz.sanxiao_check.ui.adapter.items.FireSafeChildItem;
import zhoufu.sz.sanxiao_check.ui.adapter.items.FireSafeHeaderItem;
import zhoufu.sz.sanxiao_check.ui.adapter.items.ShowPicsItem;
import zhoufu.sz.sanxiao_check.ui.contract.RefreshContract;
import zhoufu.sz.sanxiao_check.weiget.EditItemDialog;
import zhoufu.sz.sanxiao_check.weiget.ImageWithDelView;

/**
 * Created by hyc on 16-8-4.
 * 项目 ： XTSanXiao_V2
 * 开发 ： hyc
 * 时间 ： 16-8-4 上午10:54
 * 功能 ： TODO
 */

public class FireSafetyFragment extends RefreshRecyclerViewFragment
        implements RefreshContract.View<List<FireSafeHeaderItem>, CheckItemModel>
        , ShowPicsItem.OnAddDescribeListener, EditItemDialog.OnEditItemListener {

    @Inject
    Navigator _navigator;
    private final int _REQUESTCODE = 0x11;
    private final static String SID = "SID";
    private FlexibleAdapter _adapter;
    private FireSubItemAdapter _firesubAdapter;
    private ShowPicsItem _clickedShowPicsItem;
    private boolean _isSameIWD;
    private ImageWithDelView _clickedIWD;
    /**
     * 获取到展示的CheckItemModel,并更新到服务端
     */
    private CheckItemModel _checkItemModel;
    private int _position;
    private ShowPicsItem _clickedAddDesItem;
    private String _sid;

    public static FireSafetyFragment newInstance(String sid) {

        Bundle args = new Bundle();
        args.putString(FireSafetyFragment.SID, sid);
        FireSafetyFragment fragment = new FireSafetyFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public final String TAG = FireSafetyFragment.this.getClass().getName();

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(TAG, _checkItemModel);
    }


    @Override
    protected void injectThis(LoginComponet component) {
        component.inject(this);
        _recyclerViewPresenter.bindV(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState == null) {
            _sid = getArguments().getString(SID);
            _recyclerViewPresenter.pullData(_sid);
            switchRefresh(false);
        } else {
            _recyclerViewPresenter
                    .comData((CheckItemModel) savedInstanceState.getSerializable(TAG));
        }
    }


    @Override
    public void showToast(String msg) {

    }

    @Override
    public void pullFaild() {
        hideProgreesDialog();
        showErrorView();
    }

    @Override
    public void pullEnd() {
        hideProgreesDialog();
    }

    @Override
    public void pullStart() {
        showLoadView();
    }


    @Override
    public void pullSuccesed(List<FireSafeHeaderItem> models, CheckItemModel checkItemModel) {
        showContent();
        LinkedList<FireSafeHeaderItem> items = new LinkedList(models);
        if (_adapter == null) {
            _adapter = new FlexibleAdapter<>(items, this);
            _adapter.expandItemsAtStartUp()
                    .setAutoCollapseOnExpand(false)
                    .setAutoScrollOnExpand(true)
                    .setRemoveOrphanHeaders(false)
                    .setAnimationOnScrolling(true)
                    .setAnimationOnReverseScrolling(true);
            getmRecyclerView().setAdapter(_adapter);
        } else {
            _adapter.updateDataSet(items);
        }
        _checkItemModel = checkItemModel;
    }

    @Override
    public void loadMoreSuccesed(List<FireSafeHeaderItem> s) {

    }

    @Override
    public void connectWrong() {
        showConnError();
    }

    @Override
    public boolean onItemClick(FlexibleViewHolder flexibleViewHolder, FlexibleAdapter adapter,
                               int position) {
        if (adapter instanceof FireSubItemAdapter) {
            FireSubItemAdapter levelAdapter = (FireSubItemAdapter) adapter;
            boolean isSameAdapter = _firesubAdapter != null
                    && _firesubAdapter == levelAdapter;

            _firesubAdapter = levelAdapter;
            if (flexibleViewHolder instanceof DataBindingItem.ViewHolder) {

                DataBindingItem.ViewHolder holder = (DataBindingItem.ViewHolder) flexibleViewHolder;

                if (holder._dataBinding instanceof ItemShowpicBinding) {

                    _clickedShowPicsItem = (ShowPicsItem) _firesubAdapter.getItem(position);
                    ItemShowpicBinding dataBinding = (ItemShowpicBinding) holder._dataBinding;
                    /**
                     *
                     * @see 拿到点击的img,这里比较的条件需要加入 adapter
                     *
                     */
                    _isSameIWD = isSameAdapter && _clickedIWD != null &&
                            (_clickedIWD.equals(dataBinding.showpicIwd));
                    if (!_isSameIWD) {
                        _clickedIWD = dataBinding.showpicIwd;
                    }

                    if (_clickedIWD.hasDrawWithImg() || (_clickedShowPicsItem.getDB() != null
                            && !TextUtils.isEmpty(_clickedShowPicsItem.getDB().getImg()))) {
                        //展示图片
                        showImgWithList(levelAdapter, position);
                    } else {
                        //选择图片
                        //_navigator.selectImage(this, _REQUESTCODE);
                        _navigator.selectMaxOneImage(mResultCallback);
                    }
                    _position = position;
                }
            }
        }
        return true;
    }

    private GalleryFinal.OnHanlderResultCallback mResultCallback
            = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (resultList != null && resultList.size() > 0) {
                //List<String> listpath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                String url = resultList.get(0).getPhotoPath();
                if (_firesubAdapter != null) {
                    /**
                     *   当_levelAdapter的size<2
                     *   当添加新的Item时，需要调用{@link ExpandableFireHeaderItem}的addSub（） 方法
                     */
                    if ((!_isSameIWD && !_clickedIWD.hasDrawWithImg())
                            || _firesubAdapter.getItemCount() < 2) {
                        _firesubAdapter.addItem(_firesubAdapter.getItemCount(), null);
                    }
                    /**
                     * @cause 忘记将数据写入db  :（
                     */
                    DangerModel.BeforeImgsEntity db = _clickedShowPicsItem.getDB();
                    if (db == null) {
                        db = new DangerModel.BeforeImgsEntity();
                    }
                    db.setImg(url);
                    /**
                     * 通过tag 获取 特定位置的position ,更改集合在该位置的数据
                     */

                    int position = (int) _firesubAdapter.getRecyclerView()
                            .getTag();
                    FireSafeChildItem item = (FireSafeChildItem) _adapter.getItem(position);
                    DangerModel dangerModel = item.getDB();
                    if (_firesubAdapter.getRecyclerView().getId() == R.id.rv_child_before) {

                        dangerModel.setBefore_Imgs(_position, db);

                    } else {

                        dangerModel.setApplying_Imgs(_position, db);
                        dangerModel.setDisposeStatus(1);

                    }

                    _clickedShowPicsItem.setDB(db);
                    _clickedIWD.setImageSource(url);
                }
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
        }
    };

    //@Override
    //public void onActivityResult(int requestCode, int resultCode, Intent data) {
    //    super.onActivityResult(requestCode, resultCode, data);
    //    if (resultCode == Activity.RESULT_OK) {
    //        List<String> listpath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
    //        String url = listpath.get(0);
    //        if (_firesubAdapter != null && _REQUESTCODE == requestCode) {
    //            /**
    //             *   当_levelAdapter的size<2
    //             *   当添加新的Item时，需要调用{@link ExpandableFireHeaderItem}的addSub（） 方法
    //             */
    //            if ((!_isSameIWD && !_clickedIWD.hasDrawWithImg()) || _firesubAdapter.getItemCount() < 2) {
    //                _firesubAdapter.addItem(_firesubAdapter.getItemCount(), null);
    //            }
    //            /**
    //             * @cause 忘记将数据写入db  :（
    //             */
    //            DangerModel.BeforeImgsEntity db = _clickedShowPicsItem.getDB();
    //            if (db == null) {
    //                db = new DangerModel.BeforeImgsEntity();
    //            }
    //            db.setImg(url);
    //            /**
    //             * 通过tag 获取 特定位置的position ,更改集合在该位置的数据
    //             */
    //
    //            int position = (int) _firesubAdapter.getRecyclerView().getTag();
    //            FireSafeChildItem item = (FireSafeChildItem) _adapter.getItem(position);
    //            DangerModel dangerModel = item.getDB();
    //            if (_firesubAdapter.getRecyclerView().getId() == R.id.rv_child_before) {
    //                dangerModel.setBefore_Imgs(_position, db);
    //            } else {
    //                dangerModel.setApplying_Imgs(_position, db);
    //                dangerModel.setDisposeStatus(1);
    //            }
    //
    //            _clickedShowPicsItem.setDB(db);
    //            _clickedIWD.setImageSource(url);
    //        }
    //    }
    //
    //}

    private void showImgWithList(FireSubItemAdapter adapter, int position) {
        int itemCount = adapter.getItemCount();
        ArrayList<String> pics = new ArrayList<>();
        for (int i = 0; i < itemCount; i++) {
            ShowPicsItem item = (ShowPicsItem) adapter.getItem(i);
            if (item == null || item.getDB() == null) {
                continue;
            }
            //拿到图片地址
            String filePathe = item.getDB().getImg();
            if (!TextUtils.isEmpty(filePathe)) {
                pics.add(filePathe);
            }
        }
        //_navigator.goToShowPic(this, _clickedIWD.getImg(), position, pics);
        _navigator.startShowPic(mAct, TextUtils.join(",", pics));
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_save, menu);
        MenuItem item = menu.getItem(0);
        item.setTitle("下一步");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //  封装数据并跳转到整改措施页面
        if (_checkItemModel != null) {
            //            getmAct().addFragmentWithStage(R.id.main_fram, ModifyActionFragment.newInstance(_checkItemModel));
            Intent intent = new Intent(this.getActivity(), FireSafeActivity.class);
            intent.putExtra("_SID", _checkItemModel);
            this.startActivity(intent);
            getActivity().finish();
        }

        return super.onOptionsItemSelected(item);
    }

    public void onDelImg(FireSubItemAdapter adapter, int position) {
        // parentPosition 是该item 属于哪个 位置 {@link FireSafeChildItem} ?
        RecyclerView recyclerView = adapter.getRecyclerView();
        int parentPosition = (int) recyclerView.getTag();

        FireSafeChildItem item = (FireSafeChildItem) _adapter.getItem(parentPosition);
        if (recyclerView.getId() == R.id.rv_child_before) {
            item.getDB().delBefore_Imgs(position);
        } else {
            item.getDB().delApplying_Imgs(position);
        }

        if (item.getDB().getApplying_Imgs() == null || item.getDB().getApplying_Imgs().size() < 1) {
            item.getDB().setDisposeStatus(0);
        }
        if (item.getDB().getBefore_Imgs() == null || item.getDB().getBefore_Imgs().size() < 1) {
            item.getDB().setIs_Ok(0);
        }
    }

    @Override
    public boolean onItemClick(int position) {
        return super.onItemClick(position);
    }

    @Override
    public void clickAddDescriber(ShowPicsItem item, int position) {
        _clickedAddDesItem = item;
        EditItemDialog.newInstance(item.getDB().getDescribe(), position, this)
                .show(getFragmentManager(), EditItemDialog.TAG);
    }

    @Override
    public void onTitleModified(int position, String newTitle) {
        _clickedAddDesItem.getDB().setDescribe(newTitle);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.error_view) {
            _recyclerViewPresenter.pullData(_sid);
        }
    }
}
